package com.starblink.mine.personhome.ui.like.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.bean.LoadAction
import com.starblink.android.basic.brv.utils.*
import com.starblink.android.basic.ext.ApolloModelExt.isLikeOpen
import com.starblink.android.basic.ext.ApolloValSetExt
import com.starblink.android.basic.ext.commContext
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.modules.mine.MineManager
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.LikePostEvent
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.mine.R
import com.starblink.mine.databinding.FragmentLikeBinding
import com.starblink.mine.databinding.ItemSimplePostCardBinding
import com.starblink.mine.personhome.ui.SharedViewModel
import com.starblink.rocketreserver.FetchLikedPostsByAccountIdQuery
import com.starblink.rocketreserver.fragment.AccountF
import com.starblink.rocketreserver.fragment.PostF
import kotlinx.coroutines.launch

/**
 * 个人首页-Like子页面
 */
class LikeFragment : BaseTVMFragment<FragmentLikeBinding, LikeVM>() {
    var accountDeleted: Boolean = false
    var pageType: Int = MineManager.PersonHomePageType.MINE
    private val sharedViewModel by activityViewModels<SharedViewModel>()

    companion object {
        private const val TAG = "LikeFragment"
        fun newInstance(pageType: Int, accountId: String, accountDeleted: Boolean = false) =
            LikeFragment().apply {
                arguments = bundleOf(
                    MineManager.KEY_PAGE_TYPE to pageType,
                    MineManager.KEY_USER_ID to accountId,
                    MineManager.KEY_ACCOUNT_DELETED to accountDeleted
                )
            }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentLikeBinding {
        return FragmentLikeBinding.inflate(inflater, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SKLogger.e("dss", "LikeFragment-onCreate")
    }

    /**
     * 初始化数据
     */
    override fun initData() {
        arguments?.run {
            pageType = getInt(MineManager.KEY_PAGE_TYPE, MineManager.PersonHomePageType.MINE)
            getString(MineManager.KEY_USER_ID)?.let {
                viewModel.accountId = it
            }
            accountDeleted = getBoolean(MineManager.KEY_ACCOUNT_DELETED, false)
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        // 客态-如果账户已删除，仅显示Empty页面即可
        if (pageType == MineManager.PersonHomePageType.OTHER_USER && accountDeleted) {
            viewBinding.page.onEmpty {
                val tvMsg1 = findViewById<TextView>(R.id.msg2)
                tvMsg1.text = "No likes"
            }
            return
        }

        //初始化列表相关
        viewBinding.rv.itemAnimator = FadeInAnimator()
        viewBinding.rv.staggered(2).defaultDividerStagger().setup {
            addType<FetchLikedPostsByAccountIdQuery.FetchLikedPostsByAccountId, ItemSimplePostCardBinding>(it)

            onBind {
                val viewBinding = getBinding<ItemSimplePostCardBinding>()
                val post =
                    getModel<FetchLikedPostsByAccountIdQuery.FetchLikedPostsByAccountId>().postF

                // 数据Post和PostCardView控件绑定，设置点击事件
                viewBinding.card.bindPost(post, modelPosition, false, spmPageValue = SpmPageDef.MineLikeTabView) {
                    commContext().navigationTo(if (post.contentType == "1") RoutePage.Post.PAGE_PIC else RoutePage.PostVideo.PAGE_VIDEO) {
                        withString(RoutePage.Post.POST_ID, post.id)
                        withInt(RoutePage.Post.ARG_SCENE, RoutePage.Post.SCENE.ME.value)
                        withObject(RoutePage.Post.POST, post)
                    }
                }
            }
        }

        viewBinding.page.onEmpty {
            val tvMsg1 = findViewById<TextView>(R.id.msg2)
            if (it is AccountF) {
                if(it.deleted == true){
                    tvMsg1.text = "No Likes"
                }else if(!it.isLikeOpen()){
                    tvMsg1.text = "The likes is not visible."
                }
            } else {
                tvMsg1.text = "No likes yet."
            }
        }
        viewBinding.page.onLoading {
            // todo 待优化：加载中View，想要居中显示，需要动态计算其位置。并且Fragment必须支持懒加载或者ViewPager2的offscreenLimit = -1。

            // 修改视图位置
//            post {
//                val rect = Rect()
//                this.getGlobalVisibleRect(rect)
//                YYLogUtils.e("Like getGlobalVisibleRect rect = $rect", "dss")
//                val rect2 = Rect()
//                this.getLocalVisibleRect(rect2)
//                YYLogUtils.e("Like getLocalVisibleRect rect = $rect2", "dss")

//                val rect = Rect()
//                this.getGlobalVisibleRect(rect)
//                val ll = findViewById<LinearLayout>(R.id.ll_loading)
//                val lp = ll.layoutParams as FrameLayout.LayoutParams
//                lp.gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
//                YYLogUtils.e("root rect = $rect", "dss")
//                YYLogUtils.e("CommUtils.dip2px(25) = ${CommUtils.dip2px(25)}", "dss")
//                lp.topMargin = CommUtils.dip2px(25)
//            }
        }

        viewBinding.page.onRefresh {
            viewModel.getLikedPosts(refresh = true)
        }
        viewBinding.page.onLoadMore {
            viewModel.getLikedPosts(refresh = false)
        }
    }

    override fun startObserve() {
        iniEventListener()

        // 客态-如果账户已删除，仅显示Empty页面即可
        if (pageType == MineManager.PersonHomePageType.OTHER_USER && accountDeleted) {
            viewBinding.page.showEmpty()
            return
        }

        sharedViewModel.userInfoLiveData.observe(this) {
            // 客态-用户信息加载完毕
            // 如果用户账户已删除或用户Likes不允许查看，显示错误提示
            // 否则，触发刷新，加载列表数据
            if (it.deleted == true || !it.isLikeOpen()) {
                viewBinding.page.showEmpty(it)
                viewBinding.page.setEnableRefresh(false)
                viewBinding.page.setEnableLoadMore(false)
            } else {
                viewBinding.page.refresh()
            }
        }

        viewModel.listResponseLiveData.observe(this) {
            if (viewBinding.rv.models.isNullOrEmpty() || it.refresh) {
                // 刷新或页面销毁恢复
                viewBinding.page.addData(ArrayList(it.totalList)) {
                    it.totalList.size >= viewModel.ccurrencyPageNo * LikeVM.PAGE_SIZE
                }
            } else {
                // 加载更多
                viewBinding.page.addData(it.pageList) {
                    it.pageList.size >= LikeVM.PAGE_SIZE
                }
            }
        }
        viewModel.mLoadActionLiveData.observe(this) {
            when (it.action) {
                LoadAction.STATE_ERROR -> {
                    viewBinding.page.showError()
                }
            }
        }

        if (pageType == MineManager.PersonHomePageType.MINE) {
            // 主态-直接显示加载中并请求数据
            viewBinding.page.showLoading()
        } else {
            // 客态-仅显示加载中，需要等待用户信息加载完毕
            viewBinding.page.showLoading(refresh = false)
        }
    }

    private fun iniEventListener() {
        // 监听点赞发布事件
        FlowBus.with<LikePostEvent>(FlowConst.LIKE_POST_EVENT).register(this) {
//            SKLogger.e("dss", "LikeFragment-LIKE_POST_EVENT")
            // 我的个人首页-Like子页, 点赞某个发布，新增一个Post；取消点赞某个发布，修改对应post状态
            // 其他人的个人首页-Like子页，点赞某个发布或取消点赞某个发布，这个发布可能在列表中，修改对应状态
            if(it.postId.isNullOrEmpty().not() && viewModel.listResponseLiveData.value != null){
                lifecycleScope.launch {
                    for ((index, likePost) in viewModel.listResponseLiveData.value!!.totalList.withIndex()) {
                        val post = likePost.postF
                        if (it.postId == post.id && it.like != post.liked) {
//                            SKLogger.e("dss", "LikeFragment发现Post要修改")
                            ApolloValSetExt.setApolloVal<PostF>(post, "liked", it.like)
                            ApolloValSetExt.setApolloVal<PostF>(post, "likeNumbers", it.likeCount)
                            viewBinding.rv.bindingAdapter.notifyItemChanged(index)
                            break
                        }
                    }
                }
            }
        }
    }
}